Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

Valid Sudoku - 图1

A partially filled sudoku which is valid.

Note:

A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

Solution:

  1. public class Solution {
  2. public boolean isValidSudoku(char[][] board) {
  3. int n = board.length, m = board[0].length;
  4. if (n != 9 || m != 9)
  5. return false;
  6. // check rows
  7. for (int i = 0; i < 9; i++) {
  8. Set<Character> set = new HashSet<Character>();
  9. for (int j = 0; j < 9; j++) {
  10. char c = board[i][j];
  11. if (c != '.') {
  12. if (set.contains(c)) return false;
  13. set.add(c);
  14. }
  15. }
  16. }
  17. // check columns
  18. for (int j = 0; j < 9; j++) {
  19. Set<Character> set = new HashSet<Character>();
  20. for (int i = 0; i < 9; i++) {
  21. char c = board[i][j];
  22. if (c != '.') {
  23. if (set.contains(c)) return false;
  24. set.add(c);
  25. }
  26. }
  27. }
  28. // check grids
  29. for (int k = 0; k < 9; k++) {
  30. int row = k / 3 * 3;
  31. int col = k % 3 * 3;
  32. Set<Character> set = new HashSet<Character>();
  33. for (int i = 0; i < 3; i++) {
  34. for (int j = 0; j < 3; j++) {
  35. char c = board[row + i][col + j];
  36. if (c != '.') {
  37. if (set.contains(c)) return false;
  38. set.add(c);
  39. }
  40. }
  41. }
  42. }
  43. return true;
  44. }
  45. }